﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using TheMovieDB;

using Microsoft.Win32;
using System.Diagnostics;

namespace WDTVHubGen
{
  public partial class MovieSearchResultForm : Form
  {
    //List<TvdbSearchResult> m_results;
    private TmdbMovie m_selection = null;

    public MovieSearchResultForm(TmdbMovie[] movies)
    {
      InitializeComponent();

      //m_results = _searchResults;
      foreach (TmdbMovie r in movies)
      {
        ListViewItem item = new ListViewItem(r.Id.ToString());
        item.SubItems.Add(r.Name);
          if (r.Released != null) item.SubItems.Add(r.Released.Value.Year.ToString());
          item.Tag = r;
        lvSearchResult.Items.Add(item);
      }
      if (lvSearchResult.Items.Count > 0)
      {
        lvSearchResult.Items[0].Selected = true;
      }
    }

    private void cmdChoose_Click(object sender, EventArgs e)
    {
      if (m_selection == null)
      {
        lblStatus.Text = "Please select a movie first";
      }
      else
      {
        this.DialogResult = DialogResult.OK;
        this.Close();
      }
    }

    private void cmdCancel_Click(object sender, EventArgs e)
    {
      this.DialogResult = DialogResult.Cancel;
      this.Close();
    }


    public TmdbMovie Selection
    {
      get { return m_selection; }
      set { m_selection = value; }
    }

    private void lvSearchResult_AfterLabelEdit(object sender, LabelEditEventArgs e)
    {

    }

    private void lvSearchResult_SelectedIndexChanged(object sender, EventArgs e)
    {
      if (lvSearchResult.SelectedItems.Count == 1)
      {
        m_selection = (TmdbMovie)lvSearchResult.SelectedItems[0].Tag;
        
        if (m_selection != null)
        {
            for (int i = 0; i < m_selection.Images.Length; i++)
            {
                if ((m_selection.Images[i].Type == TmdbImageType.poster) && (m_selection.Images[i].Size == "cover"))
                
                {
                    pictureBox1.LoadAsync(m_selection.Images[i].Url);
                    
                    break;
                }
            }
          
        }

        txtOverview.Text = m_selection.Overview;
        linkImdb.Text = m_selection.ImdbId.Equals("")? "": "http://www.imdb.com/title/" + m_selection.ImdbId;
          if (m_selection.Released != null) txtFirstAired.Text = m_selection.Released.Value.ToShortDateString();
      }
    }

    private void linkImdb_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
    {
      Process.Start(linkImdb.Text);
    }

  }
}
